package com.bjsxt.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * web 安全配置
 * 
 * @author michael
 * @date 2021/06/23
 * @version 1.0
 * @Copyright Copyright (c) 2021, michael.xie@adsnova.cn All Rights Reserved. 
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    /**
     * http安全组件
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        // 禁用跨域
        http.csrf().disable();
        // 所有的请求都开启鉴权
        http.authorizeRequests().anyRequest().authenticated();
    }
    

    /**
     * 注入验证管理器
     */
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
         return super.authenticationManager();
    }
    
    /**
     * 注入userDetaiService
     */
    @Bean
    protected UserDetailsService userDetailsService() {
        // 模拟内存中的用户信息  采用内存中的实现类
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        // 创建用户信息
        User user = new User("admin", "123456", Arrays.asList(new SimpleGrantedAuthority("Role_Admin")));
        inMemoryUserDetailsManager.createUser(user);
        return inMemoryUserDetailsManager;
    }

    /**
     * 注入密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        
        // 先采用简单的加密方式  不加密方式
        return NoOpPasswordEncoder.getInstance();
    }
}
